package com.leozhang.app;

import org.apache.commons.cli.*;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.Security;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.crypto.spec.SecretKeySpec;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import com.alibaba.nacos.client.identify.Base64;

public class App {

    @SuppressWarnings("unused")
    private static class TrustAnyHostnameVerifier implements HostnameVerifier {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }

    private static class TrustAnyTrustManager implements X509TrustManager {

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

        }

        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[]{};
        }
    }

    public static boolean downloadCheckScript(String downloadUrl, String path) {
            URL url = null;
            FileOutputStream fileOutputStream = null;
            InputStream inputStream = null;
            try {
                url = new URL(downloadUrl);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                if (conn instanceof HttpsURLConnection) {

                    SSLContext sc = SSLContext.getInstance("TLSv1.2");
                    sc.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new java.security.SecureRandom());
                    ((HttpsURLConnection) conn).setSSLSocketFactory(sc.getSocketFactory());

                    // Use default hostname verifier, always return false
                    // ((HttpsURLConnection) conn).setHostnameVerifier(HttpsURLConnection.getDefaultHostnameVerifier());

                    ((HttpsURLConnection) conn).setHostnameVerifier((hostname, session) -> {
                        System.out.println("hostname: " + hostname + ", session: " + session);
                        String privateIPPattern = "^(10\\.|192\\.168\\.|172\\.(1[6-9]|2[0-9]|3[0-1])\\.).*";
                        return hostname.matches(privateIPPattern);
                    });

                    // ((HttpsURLConnection) conn).setHostnameVerifier(new TrustAnyHostnameVerifier());
                }
                conn.connect();
                inputStream = conn.getInputStream();
                byte[] buffer = new byte[1024];
                int length;
                String[] fileNamePath = downloadUrl.split("/");
                fileOutputStream = new FileOutputStream(path + File.separator + fileNamePath[fileNamePath.length-1]);
                while ((length = inputStream.read(buffer)) != -1) {
                    fileOutputStream.write(buffer, 0, length);
                }
                inputStream.close();
                fileOutputStream.flush();
                fileOutputStream.close();
                conn.disconnect();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return true;
        }

        static {
            Security.addProvider(new BouncyCastleProvider()); // 注册 BouncyCastle 提供程序
        }

        public static String decrypt(String encryptedData) throws Exception {
            String SECRET_KEY = "HfkdIzPG4/eZD0S=";
            String ALGORITHM = "AES";
            String INIT_VECTOR = "TBawpOJlNkb5K+9=";
            String TRANSFORMATION = "AES/CBC/PKCS5Padding";

            // 将Base64编码的字符串转换为字节数组
            byte[] encryptedBytes = Base64.decodeBase64(encryptedData.getBytes());

            // 创建密钥和初始化向量
            SecretKeySpec keySpec = new SecretKeySpec(SECRET_KEY.getBytes(), ALGORITHM);
            IvParameterSpec ivSpec = new IvParameterSpec(INIT_VECTOR.getBytes());

            // 初始化Cipher对象
            // Cipher cipher = Cipher.getInstance(TRANSFORMATION, "BC");
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);

            // 执行解密操作
            byte[] decrypted = cipher.doFinal(encryptedBytes);

            // 返回解密后的字符串
            return new String(decrypted);
        }

        public static void main(String[] args) {
            String pass = "Q4BgHZCgIaa3bVg1ZPbw0g==";
            try {
                String decryptedPass = decrypt(pass);
                System.out.println("Decrypted password: " + decryptedPass);
            } catch (Exception e) {
                e.printStackTrace();
            }
            // Options options = new Options();

            // Option urlOption = new Option("u", "url", true, "URL of the file to download");
            // urlOption.setRequired(true);
            // options.addOption(urlOption);

            // Option fileOption = new Option("f", "file", true, "file path");
            // fileOption.setRequired(true);
            // options.addOption(fileOption);

            // CommandLineParser parser = new DefaultParser();
            // HelpFormatter formatter = new HelpFormatter();
            // String fileUrl = null;
            // String filePath = null;
            // try {
            //     CommandLine cmd = parser.parse(options, args);
            //     fileUrl = cmd.getOptionValue("url");
            //     filePath = cmd.getOptionValue("file");
            // } catch (ParseException e) {
            //     System.out.println(e.getMessage());
            //     formatter.printHelp("", options);
            //     System.exit(1);
            // }

            // System.out.println("Will save " + fileUrl + " to: " + filePath);
            // downloadCheckScript(fileUrl, filePath);
        }
}
